package com.thrift.client.config;

import org.apache.commons.pool.BasePoolableObjectFactory;
import org.apache.thrift.transport.TSocket;

/**
 * @author 何锦涛--CodeSleep
 * @since 2022/9/5 21:10
 */
public class ConnectionFactory extends BasePoolableObjectFactory {

    // 远端地址
    private String host;
    // 端口
    private Integer port;
    // 服务名
    private String serviceName;

    // 构造方法初始化地址及端口
    public ConnectionFactory(String ip, int port, String serviceName) {
        this.host = ip;
        this.port = port;
        this.serviceName = serviceName;
    }

    // 创建一个对象
    @Override
    public Object makeObject() throws Exception {
        // 实例化一个自定义的 TTSocket 对象
        TTSocket ttSocket = new TTSocket(host, port, serviceName);
        ttSocket.open();
        return ttSocket;
    }

    // 销毁对象
    public void destroyObject(Object obj) {
        try {
            if (obj instanceof TSocket) {
                //尝试关闭连接
                ((TSocket) obj).close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 校验对象是否可用
     * 通过 pool.setTestOnBorrow(boolean testOnBorrow) 设置
     * 设置为true这会在调用pool.borrowObject()获取对象之前调用这个方法用于校验对象是否可用
     * @param obj 待校验的对象
     */
    public boolean validateObject(Object obj) {
        if (obj instanceof TTSocket) {
            TTSocket socket = ((TTSocket) obj);
            return socket.isOpen();
        }
        return false;
    }
}
